<template>
  <div class="app-container">
    <u-page v-if="!scheduleChoosed.id" title="返券操作">
      <div slot="header">
        <el-button icon="el-icon-search" type="primary" @click="dialogFormVisible=true">选择档期活动主题</el-button>
      </div>
    </u-page>
    <!--  选择档期主题   -->
    <u-dialog title="选择档期活动主题" :show.sync="dialogFormVisible" width="700px" @confirm="chooseSchedule">
      <el-form>
        <el-form-item label="档期主题" prop="scheduleId">
          <Schedule v-model="schedule" type-id="3" valid="valid" width="500px" @change="changeScheduleQuery" />
        </el-form-item>
      </el-form>
    </u-dialog>
    <!--  返券页面  -->
    <div v-if="scheduleChoosed.id">
      <u-page :title="scheduleChoosed.id === ''? '返券操作':scheduleChoosed.name">
        <div slot="header">
          <el-button icon="el-icon-search" type="primary" @click="dialogFormVisible=true">选择档期活动主题</el-button>
        </div>
        <u-filtered>
          <el-form :inline="true" class="search-form">
            <el-form-item label="会员卡号" prop="card_no">
              <el-input v-model="card_no" clearable placeholder="输入会员卡号" style="width: 170px" />
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="queryOrder()">查询今日活动消费情况</el-button>
            </el-form-item>
          </el-form>
        </u-filtered>
      </u-page>

      <div class="operation">
        <u-page title="满足活动规则订单" style="width:48%">
          <div slot="header">
            <span style="font-size: 10px;color:#4CAF50;">累计金额: {{ totalAmount }}</span>
          </div>
          <el-table
            ref="table"
            :data="orderList"
            style="width: 100%"
            show-checkbox
            :selection="orderChooseList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              prop="sale_time"
              label="交易时间"
              type="selection"
            />
            <el-table-column
              prop="saleNo"
              label="订单号"
            />
            <el-table-column
              prop="saleAmount"
              label="订单金额"
            />
            <el-table-column
              prop="validAmount"
              label="有效金额"
            />
          </el-table>
        </u-page>
        <u-page title="各级距活动" style="width:48%">
          <div slot="header">
            <span style="font-size: 10px;color:#4CAF50">领取所需门槛: {{ sumThreshold }}</span>
          </div>
          <el-table
            :data="operationCouponList"
            style="width: 100%"
          >
            <el-table-column
              prop="name"
              label="活动级距"
            />
            <el-table-column
              prop="couponName"
              label="活动券"
            />
            <el-table-column
              prop="threshold"
              label="领取门槛"
            >
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <div slot="reference" class="name-wrapper">
                    <span style="font-weight:bold;color:#4CAF50 !important;">{{ scope.row.threshold }}元</span>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div v-if="scope.row.flag === -1">
                  <el-button type="info" round disabled>已领取</el-button>
                </div>
                <div v-else-if="scope.row.flag === 0">
                  <el-button type="info" round disabled>领完啦</el-button>
                </div>
                <div v-else>
                  <div v-if="scope.row.selected">
                    <el-button type="success" round @click="choose(scope)">已选择</el-button>
                  </div>
                  <div v-else>
                    <el-button type="primary" round @click="choose(scope)">可选择</el-button>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" style="float:right;margin:20px;" :disabled="!(totalAmount>=sumThreshold&&sumThreshold>0)" @click="getToken">发放优惠券</el-button>
        </u-page>
      </div>
    </div>
    <!--  返券二维码-->
    <div v-if="qrCodeVisible" style="position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(0,0,0,0.3);z-index: 9999">
      <div style="padding:20px;width:300px;height:340px;background-color: #fff;margin: 0 auto; margin-top:150px;">
        <div style="text-align: center;margin-bottom:20px;"><span style="font-size:18px;">扫码领券</span></div>
        <!-- 二维码图片 -->
        <div id="qrCodeUrl" />
        <div style="text-align: center;margin-top:20px;"><span style="font-size:18px;">二维码有效时间：{{ second }}秒</span></div>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import Schedule from '../../components/schedule'
export default {
  components: {
    Schedule
  },
  data() {
    return {
      sumThreshold: 0, // 累计门槛金额
      totalAmount: 0, // 累计金额
      tableData: [], // 表格数据
      orderChooseList: [], // 选中的行数据
      count: 0, // 可领取张数
      second: 20,
      qrCodeVisible: false, // 二维码弹框
      api: this.$u.api.RebatenewRebatecoupon,
      dialogFormVisible: true, // 选择主题弹框
      schedule: {},
      scheduleChoosed: {}, // 选择的档期主题
      card_no: '',
      // 小票明细
      orderList: [],
      operationCouponList: [],
      // 表格
      columns: [
        {
          prop: 'sale_time',
          label: '交易时间'
        },
        {
          prop: 'saleNo',
          label: '订单号'
        },
        {
          prop: 'saleAmount',
          label: '订单金额'
        },
        {
          prop: 'validAmount',
          label: '有效金额'
        }
      ],
      listOptions: {
        mutiSelect: false,
        stripe: true
      }
    }
  },
  created() {
  },
  methods: {
    changeScheduleQuery(item) {
      this.schedule = item
    },
    // 选择主题
    chooseSchedule() {
      console.log(typeof (this.schedule))
      if (this.schedule.id === '' || typeof (this.schedule.id) === 'undefined') {
        alert('请选择档期主题')
      } else {
        this.dialogFormVisible = false
        this.scheduleChoosed = this.schedule
      }
    },
    // 选择活动
    choose(scope) {
      console.log(scope)
      console.log(scope.$index)
      const index = scope.$index
      const operationCouponList = this.operationCouponList
      operationCouponList[index].selected = !operationCouponList[index].selected // 改变订单状态
      this.operationCouponList = operationCouponList
      this.getSumThreshold()
    },
    getSumThreshold() {
      let sumThreshold = 0
      const operationCouponList = this.operationCouponList
      for (let i = 0; i < operationCouponList.length; i++) {
        if (operationCouponList[i].selected) {
          sumThreshold += operationCouponList[i].threshold
        }
      }
      this.sumThreshold = sumThreshold
      console.log('门槛', sumThreshold)
    },
    // 查询会员可返券订单列表
    queryOrder() {
      this.orderList = []
      const card_no = this.card_no
      if (card_no === '') {
        return
      }
      this.listLoading = true
      // 活动
      this.api.queryDJMZOperByScheduleId({
        'scheduleId': this.scheduleChoosed.id,
        'card_no': this.card_no
      }).then(res => {
        this.operationCouponList = res.data
      })
      // 获取订单
      this.api.getRebateOrdersMZ({
        'card_no': card_no,
        'scheduleId': this.scheduleChoosed.id
      }).then(res => {
        const dataList = res.data
        if (dataList.length === 0) {
          this.$message.error('无满足活动规则订单')
        } else {
          this.orderList = dataList
        }
        console.log(res)
        // 关闭加载状态
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // sub() {
    //   // 模态对话框组件
    //   this.$confirm('是否确认发券？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
    //     this.rebate()
    //   })
    // },
    async rebate(token) {
      const chooseOperList = []
      const operationCouponList = this.operationCouponList
      for (let i = 0; i < operationCouponList.length; i++) {
        if (operationCouponList[i].selected) {
          chooseOperList.push(operationCouponList[i])
        }
      }
      console.log(this.orderChooseList)
      console.log(chooseOperList)
      this.api.rebatecouponLJDJMZbytoken({
        'card_no': this.card_no,
        'token': token,
        'operationCouponList': chooseOperList,
        'approachType': 1,
        'orderList': this.orderChooseList,
        'sumThreshold': this.sumThreshold
      }).then(res => {
        if (res.data != null && res.data !== '') {
          this.orderList = []
          this.operationCouponList = []
          this.sumThreshold = 0
          this.$u.msg('返券成功')
        } else {
          this.$message.error('券已达领取上限')
        }
        this.qrCodeVisible = false
      }).catch(err => {
        this.$message.error(err.msg)
        this.qrCodeVisible = false
      })
    },
    // 获取token 发券操作
    async getToken() {
      this.api.rebatesendtoken().then(res => {
        this.qrCodeGeneration(res.data)
        this.rebate(res.data)
      })
    },
    // 二维码生成
    qrCodeGeneration(token) {
      this.countdown()
      const url = 'https://csms.chiconysquare.net/mp/qr/rebate?type=' + this.scheduleChoosed.type + '&token='
      // 二维码弹框显示
      this.qrCodeVisible = true
      // 生成二维码
      this.$nextTick(function() {
        document.getElementById('qrCodeUrl').innerHTML = ''
        const qrCodeUrl = new QRCode('qrCodeUrl', {
          width: 200,
          height: 200,
          text: url + token,
          colorDark: '#409EFF',
          colorLight: '#fff'
        })
      })
    },
    // 二维码倒计时
    countdown() {
      this.second = 20
      var countDown = setInterval(() => {
        if (this.second < 1) {
          this.second = 20
          this.qrCodeVisible = false
          clearInterval(countDown)
        } else if (this.second >= 0) {
          this.second--
        }
      }, 1000)
    },
    handleSelectionChange(selection) {
      this.orderChooseList = selection
      console.log(selection)
      const total = selection.reduce((accumulator, currentRow) => {
        return accumulator + currentRow.validAmount
      }, 0)
      this.totalAmount = total
    },
    selectAllRows() {
      this.$refs.table.toggleAllSelection()
    }
  }
}
</script>
<style lang="scss" scoped>
.operation{
  display: flex;
  justify-content: space-around;
  padding:10px 20px;
  margin-top:10px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  align-items: flex-start;
}
::v-deep .el-dialog__header {
  text-align: center;
}

::v-deep #qrCodeUrl > img {
  margin: 0 auto;
}
</style>
